<?php

namespace app\api\service\google;

use app\model\language\LanguageCodesModel;
use app\service\http\google\maps\HttpGoogleMaps;
use app\service\http\google\translation\HttpGoogleTranslation;
use hunma\exception\ApiException;
use support\Redis;

class GoogleService
{

    public function latlng(array $getAllParams)
    {
        // 检查是否需要缓存数据
        $isCache = isset($getAllParams['isCache']) ?? true;
        $cacheKey = 'google_latlng_' . md5($getAllParams['address']);

        if($isCache){
            // 检查缓存
            $cachedData = Redis::get($cacheKey);
            if ($cachedData) {
                return json_decode($cachedData);
            }
        }

        $httpGoogleMaps = new HttpGoogleMaps();

        $resData = $httpGoogleMaps->geocode($getAllParams['address']);
        // 存入缓存
        if ($isCache && $resData) {
            Redis::setEx($cacheKey, 36000, json_encode($resData, JSON_UNESCAPED_UNICODE));
        }

        return $resData;
    }

    public function translate(array $getAllParams)
    {
        // 检查是否需要缓存数据
        $isCache = isset($getAllParams['isCache']) ?? true;
        $cacheKey = 'google_translate_' . md5($getAllParams['content'].$getAllParams['target']);

        if($isCache){
            // 检查缓存
            $cachedData = Redis::get($cacheKey);
            if ($cachedData) {
                return json_decode($cachedData);
            }
        }

        // target传入的是中文，需要转获取到对应的语言
        $code = LanguageCodesModel::getOne(['name'=>$getAllParams['target']],'code');
        if(isset($code['code']) && $code['code']){
            $getAllParams['target'] = $code['code'];
        } else {
            throw new ApiException('目标语言不存在');
        }

        $httpGoogleTranslation = new HttpGoogleTranslation();

        $resData = $httpGoogleTranslation->translate($getAllParams);
        // 存入缓存
        if ($isCache && $resData) {
            Redis::setEx($cacheKey, 36000, json_encode($resData, JSON_UNESCAPED_UNICODE));
        }

        return $resData;
    }
}